<template>
  <div class="favorites-container">
    <!-- 顶部状态筛选 -->
    <el-affix :offset="0">
      <el-tabs 
        v-model="activeStatus" 
        class="status-tabs"
        @tab-change="filterProductsByStatus"
      >
        <el-tab-pane label="全部" name="全部"></el-tab-pane>
        <el-tab-pane label="已下架" name="已下架"></el-tab-pane>
      </el-tabs>
    </el-affix>

    <!-- 商品列表 -->
    <el-scrollbar class="product-scrollbar" @scroll="handleScroll">
      <div class="product-list">
        <el-card 
          v-for="product in displayedProducts" 
          :key="product.id" 
          class="product-card"
          shadow="hover"
        >
          <div class="product-content">
            <el-image 
              class="product-image" 
              :src="product.image || 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png'"
              fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-meta">
                <div class="product-price">¥{{ product.price }}</div>
                <el-tag 
                  v-if="product.status === '下架'" 
                  type="danger" 
                  size="small"
                >
                  已下架
                </el-tag>
              </div>
              <div class="product-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="wantProduct(product.product_code)"
                >
                  我想要
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  plain
                  @click="removeFavorite(product.product_code)"
                >
                  取消收藏
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 加载更多 -->
        <div v-if="loading" class="loading-more">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div v-if="noMoreData" class="no-more-data">
          没有更多数据了
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Picture, Loading } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '@/utils/request'

// 商品数据
const products = ref([])
const activeStatus = ref('全部')
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const noMoreData = ref(false)
const totalProducts = ref(0)

// 筛选后的商品
const filteredProducts = computed(() => {
  if (activeStatus.value === '全部') {
    return products.value
  } else {
    return products.value.filter(p => p.status === 0) // 假设0表示下架
  }
})

// 显示的商品
const displayedProducts = computed(() => {
  return filteredProducts.value.slice(0, page.value * pageSize.value)
})

// 状态切换
const filterProductsByStatus = (status) => {
  activeStatus.value = status
  page.value = 1
  noMoreData.value = false
  fetchFavoriteProducts()
}

// 想要商品
const wantProduct = (productCode) => {
  const product = products.value.find(p => p.product_code === productCode)
  if (product?.status === 0) {
    ElMessage.warning('该商品已下架，无法购买')
    return
  }
  ElMessage.success(`跳转到商品 ${productId} 的详情页`)
}

// 取消收藏
const removeFavorite = async (productCode) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消收藏该商品吗？',
      '取消收藏确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // 示例调用接口：DELETE /products/buyer/favorites/{productId}/
    await apiClient.delete(`/api/products/buyer/${productCode}/favorites/`)
    products.value = products.value.filter(p => p.product_code !== productCode)
    ElMessage.success('已取消收藏')
  } catch {
    ElMessage.info('已取消操作')
  }
}


// 获取收藏商品
const fetchFavoriteProducts = async () => {
  try {
    loading.value = true
    const response = await apiClient.get('/api/products/buyer/favorites/', {
      params: { page: page.value }
    })
    console.log('收藏返回数据：', response.data)

    const newProducts = response.data.results.map(item => ({
      id: item.id,
      name: item.name,
      price: item.price,
      status: item.status,
      image: item.images?.[0]?.url || '',
      product_code: item.product_code,
      description: item.description,
      delivery_location: item.delivery_location
    }))

    if (page.value === 1) {
      products.value = newProducts
    } else {
      products.value = [...products.value, ...newProducts]
    }

    if (newProducts.length < pageSize.value) {
      noMoreData.value = true
    }
  } catch (error) {
    ElMessage.error('获取收藏商品失败')
    console.error('Error fetching favorite products:', error)
  } finally {
    loading.value = false
  }
}

// 滚动加载更多
const handleScroll = ({ scrollTop, clientHeight, scrollHeight }) => {
  const isNearBottom = scrollHeight - scrollTop <= clientHeight + 50
  if (isNearBottom && !loading.value && !noMoreData.value) {
    loadMore()
  }
}

// 加载更多数据
const loadMore = () => {
  if (noMoreData.value) return
  page.value++
  fetchFavoriteProducts()
}

// 初始化
onMounted(() => {
  fetchFavoriteProducts()
})
</script>

<style scoped>
.favorites-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.status-tabs {
  background-color: var(--el-bg-color);
  padding: 0 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.status-tabs :deep(.el-tabs__header) {
  margin: 0;
}

.status-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.product-scrollbar {
  flex: 1;
  padding: 20px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.product-card {
  transition: all 0.3s;
  border-radius: 8px;
}

.product-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.1);
}

.product-content {
  display: flex;
  gap: 15px;
}

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.product-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 10px;
}

.loading-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.no-more-data {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
}
</style>